﻿using BarcodeDelay.bean;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class CancelChangeAddrHelperGen
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListCancelsBarcodes = new ArrayList();
        public event Action CancelsEvent;

        private static CancelChangeAddrHelperGen instance;
        public static CancelChangeAddrHelperGen Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new CancelChangeAddrHelperGen();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList arListBarCodes, string anayType)
        {
            try
            {
                initLog();
                m_arListCancelsBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }


                m_arListCancelsBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseCancels));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;
              

            }
            catch (Exception ex)
            {

            }
        }



        public void parseCancels(object arListBarcodes)
        {
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                JArray wayBills = new JArray();
                string lastBarcode = "";
                foreach (ParcelBean parcelBean in (ArrayList)arListBarcodes)
                //foreach (string strBarCode in (ArrayList)arListBarcodes)
                {
                    string strBarCode = parcelBean.wayBill;
                   
                    lastBarcode = strBarCode.Trim();
                    string pickName = "";
                    string orderSource = "";
                    string curSiteToken = "";
                    string customerName = "";
                    if (!UtilityHelp.Instance.resetToken(strBarCode.Trim(),out pickName,out orderSource,out curSiteToken,out customerName))
                    {
                        if (curSiteToken == "")
                        {
                            StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 登录失效";
                            continue;
                        }
                        StoParams.Instance.htResWechat[lastBarcode] = " 发件网点 "+ pickName+ " 非我司单号  无法处理";
                        continue;
                    }
                    parcelBean.lanshouSite = pickName;
                    parcelBean.customerName = customerName;

                    ArrayList arListAllGXTask = new ArrayList();
                    string httpRes = "";
                    ArrayList arListRoadMap = JTDelayHelper.Instance.getRoadMap(parcelBean.wayBill, out httpRes, arListAllGXTask);
                    string lanshouTime = JTDelayHelper.Instance.getLanShouTime(arListRoadMap);
                    parcelBean.lanshouTime = lanshouTime;
                    parcelBean.replyType = "撤销改地址";
                    wayBills.Add(strBarCode.Trim());
                }

                if(wayBills.Count==0)
                {
                    return;
                }


           

                


                JObject jObjDetail = new JObject();
                jObjDetail["waybillIds"] = wayBills;
                jObjDetail["reason"] = "";
                jObjDetail["countryId"] = "1";

                string strUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/rebackTransferExpress/revocation";
                if (StoParams.Instance.isRabbitWin)
                {
                    strUrl = "https://wdgw.jtexpress.com.cn/ops/wdbutler/rebackTransferExpress/revocation";
                }

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObjDetail);
                string res = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, "interceptQueryBackNew");

                StoParams.Instance.resMsg = "";


                

                if (!res.Contains("请求成功"))
                {
                    if (res.Contains("msg"))
                    {
                        JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                        JToken msgToken = jsonObjRes["msg"];
                        res = msgToken.ToString();
                    }

                    StoParams.Instance.htResWechat[lastBarcode] = " 撤销改地址失败 " + res;
                    StoParams.Instance.curFailedBarcode = lastBarcode;
                    StoParams.Instance.resMsg = lastBarcode + " 撤销改地址失败 " + res;

                   

                }
                else
                {
                    JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                    JToken sucToken = (JToken)jsonObjRes["succ"];
                    if (sucToken.ToString().ToLower() == "true")
                    {
                        StoParams.Instance.resMsg = "撤销改地址成功";
                        StoParams.Instance.htResWechat[lastBarcode] = "撤销改地址成功";
                        StoParams.Instance.currentBarcode = lastBarcode;
                        StoParams.Instance.resMsg = lastBarcode + " 撤销改地址成功";
                    }
                    
                }

                resMsg = StoParams.Instance.resMsg;
                StoParams.Instance.htResWechat[lastBarcode] = resMsg;
                if(CancelsEvent!=null)
                {
                    CancelsEvent.Invoke();
                }
                
               

            }
            catch (Exception ex)
            {
                

            }
            int tiot = queryServerResTime;
           


        }






        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
